#include <buola/media/codec/bffmpegdecoder.h>

#include "cinputcontext.h"
#include "cinputaudiostream.h"
#include "cinputvideostream.h"

#include <buola/utility/placeholders.h>

namespace buola { namespace media {

BFfmpegDecoder::BFfmpegDecoder()
    :   BBox("ffmpeg decoder")
    ,   iData(this,"data in")
{
//    iData.SetPushBufferCB(std::bind(&BFfmpegDecoder::PushBufferCB,this,_1));
}

BFfmpegDecoder::~BFfmpegDecoder()
{

}

void BFfmpegDecoder::Loop()
{
    assert(GetState()==STATE_ACTIVE);

    mCtx->ProcessNextFrame();
}

void BFfmpegDecoder::DoInitialize()
{
    ffmpeg::init_ffmpeg();
}

void BFfmpegDecoder::DoActivate()
{
    mCtx.reset(new ffmpeg::CInputContext);
    mCtx->Open(iData);

    mCtx->FindStreams();

    for(ffmpeg::CInputAudioStream *lStream : mCtx->AudioStreams())
    {
        SAudio *lAudio=new SAudio;
        
        lAudio->mStream.reset(lStream);
        
        lAudio->oAudio=new blackbox::CStreamOut<int16_t>(this,"audio out "+to_string(oAudio.size()+1));
        oAudio.push_back(lAudio->oAudio);
        lStream->SetPorts(lAudio->oAudio);

        mAudio.emplace_back(lAudio);
    }

    for(ffmpeg::CInputVideoStream *lStream : mCtx->VideoStreams())
    {
        SVideo *lVideo=new SVideo;
        
        lVideo->mStream.reset(lStream);
        
        lVideo->oVideo=new blackbox::CDataOut<img::CImage_rgb8>(this,"video out "+to_string(oVideo.size()+1));
        oVideo.push_back(lVideo->oVideo);
        lVideo->kVideo=new blackbox::CClockOut(this,"video clock "+to_string(kVideo.size()+1));
        kVideo.push_back(lVideo->kVideo);
        lStream->SetPorts(lVideo->oVideo,lVideo->kVideo);

        mVideo.emplace_back(lVideo);
    }
}

/*namespace media*/ } /*namespace buola*/ }
